package com.atguigu.datasource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * projectName: day04_jdbc
 *
 * @author: 赵伟风
 * time: 2021/11/26 17:09
 * description:基于Druid连接池进行连接的获取和回收！
 *     todo 基于外部的配置文件！
 */
public class JdbcPoolV2 {

    private static DataSource dataSource = null;

    static {

        Properties properties = new Properties();
        InputStream asStream = JdbcPoolV2.class.getClassLoader().getResourceAsStream("jdbc.properties");

        try {
            properties.load(asStream);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取连接连接的方法
     * @return 返回连接池中的连接
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {

        return dataSource.getConnection();
    }


    /**
     * 回收连接
     * @param connection 需要回收的连接！ 注意，必须是连接池取出的连接
     * @throws SQLException
     */
    public static void  close(Connection connection) throws SQLException{

        if (connection != null) {
            connection.close();
        }

    }
}
